import {useCallback, useState} from "react";

const URL_PREFIX = "http://localhost:1337/api/";
/**
 * React 中的钩子函数只能在函数组件或者自定义钩子中调用
 * 自定义钩子其实就是一个普通的函数,只不过函数名需要以use开头
 */
/**
 *  {
 *    url: "students",
 *    method: "",
 *  }
 * @param reqObj
 * @param callBack 回调函数 请求发送成功后调用
 * @returns {{fetchData: ((function(): Promise<void>)|*), data: *[], loading: boolean, error: unknown}}
 */
export default function useFetch(reqObj, callBack) {

	const [data, setData] = useState([]);
	const [loading, setLoading] = useState(false);
	const [error, setError] = useState(null);

	const fetchData = useCallback(async (body) => {
		try {
			setLoading(true);
			setError(null);
			const resp = await fetch(URL_PREFIX + reqObj.url, {
				method: reqObj.method || 'get',
				headers: {
					"Content-type": "application/json"
				},
				"body": body ? JSON.stringify({data: body}) : null,		// ???
			});

			if (resp.ok) {
				// 没传 method (说明是get请求) 或者传了不是 delete
				if (!reqObj.method || reqObj.method.toLowerCase() !== "delete") {
					const result = await resp.json();
					setData(result.data);
				}
				callBack && callBack();			// 传了回调函数就调用, 没传就不调用
			} else {
				throw new Error("数据加载失败!");
			}
			setLoading(false);
		} catch (error) {
			console.log(error);
			setError(error);
		} finally {
			setLoading(false);
		}
	}, []);

	return {
		data,
		loading,
		error,
		fetchData
	}

}
